﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using USMCdotNET;
using System.Threading.Tasks;
using System.Diagnostics;

namespace USMC.Net
//сделать  приметив прямоугольника для цикла!!!
{
    delegate void Update(ref PointParameters p);
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer timer;
        bool isFloawable = false;
        //таймер отключения
        DispatcherTimer shutDownTimer;
        //объект для отмены движения
        System.Threading.CancellationTokenSource movementCancel;

        Checker checker;

        public MainWindow()
        {
            InitializeComponent();

            Trace.Listeners.Add(new TextBoxTraceListener(logTextBox));
            Trace.AutoFlush = true;

            Trace.WriteLine("Главная форма запущена");
            InitializeStateTextBoxes();
            InitializeModeTextBoxes();
            InitializeParametersBoxes();
            //   SetlineScrollViewerParameters(ref canvas.standardParameters);
            this.CaptureMouse();
            canvas.SelectionChanged += new Action<object>(canvas_SelectionChanged);
            timer = new System.Windows.Threading.DispatcherTimer();
            timer.Tick += new EventHandler(timerTick);
            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Start();
            PreviewKeyDown+=new KeyEventHandler(point_KeyDown);
            Keyboard.Focus(this);
            canvas.cyclesMenuItemSeelected += new EventHandler(canvas_cyclesMenuItemSeelected);
        }
        private void closeCyclesButton_Click(object sender, RoutedEventArgs e)
        {
            routTabItem.Visibility = Visibility.Visible;
            deviceTabItem.Visibility = Visibility.Visible;
            routeinStackButton.Visibility = Visibility.Collapsed;
            deviceinStackButton.Visibility = Visibility.Collapsed;
            tabControl1.SelectedIndex = 0;
            tabControl1.Width = Double.NaN;
            isFloawable = false;
            splitter1.Visibility = Visibility.Visible;
            tabControl1.Visibility = Visibility.Visible;
            cyclesList.UnassignPointsStack();
            cyclesTabItem.Visibility = Visibility.Collapsed;
        }
        void canvas_cyclesMenuItemSeelected(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
            tabControl1.Width = Double.NaN;
            routTabItem.Visibility = Visibility.Collapsed;
            deviceTabItem.Visibility = Visibility.Collapsed;
            routeinStackButton.Visibility = Visibility.Collapsed;
            deviceinStackButton.Visibility = Visibility.Collapsed;
            isFloawable = false;
            splitter1.Visibility = Visibility.Visible;
            tabControl1.Visibility = Visibility.Visible;
            cyclesTabItem.Visibility = Visibility.Visible;
            PointControl currentPoint = (PointControl)sender;
            cyclesList.AssignPointsStack(currentPoint);
            MouseButtonEventHandler handler =null;
            handler = new MouseButtonEventHandler((object s, MouseButtonEventArgs ea) =>
            {
                closeCyclesButton_Click(null, null);
                canvas.pointsCanvas.MouseDown -= handler;
                canvas.mainCanvas.MouseDown -= handler;
            });
            canvas.pointsCanvas.MouseDown += handler;
            canvas.mainCanvas.MouseDown += handler;
        }

        

        #region панель инструментов
        private void routTabItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(controlsGrid);
            if (p.Y < 0)
            {
                routTabItem.Visibility = Visibility.Collapsed;
                routeinStackButton.Visibility = Visibility.Visible;
                if (routTabItem.Visibility == Visibility.Collapsed && deviceTabItem.Visibility == Visibility.Collapsed)
                {
                    tabControl1.Visibility = Visibility.Collapsed;
                    splitter1.Visibility = Visibility.Collapsed;
                    mainGrid.ColumnDefinitions[1].MinWidth = 0;
                    isFloawable = true;
                }
                else
                {
                    tabControl1.SelectedIndex = 1;
                }
            }
        }

        private void deviceTabItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(deviceScrollView);
            if (p.Y < 0)
            {
                deviceTabItem.Visibility = Visibility.Collapsed;
                deviceinStackButton.Visibility = Visibility.Visible;
                if (routTabItem.Visibility == Visibility.Collapsed && deviceTabItem.Visibility == Visibility.Collapsed)
                {
                    tabControl1.Visibility = Visibility.Collapsed;
                    splitter1.Visibility = Visibility.Collapsed;
                    mainGrid.ColumnDefinitions[1].MinWidth = 0;
                    isFloawable = true;
                }
                else
                {
                    tabControl1.SelectedIndex = 0;
                }
            }
        }

        private void routeinStackButton_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            routTabItem.Visibility = Visibility.Visible;
            routeinStackButton.Visibility = Visibility.Collapsed;
            tabControl1.SelectedIndex = 0;
            tabControl1.Width = Double.NaN;
            isFloawable = false;
            splitter1.Visibility = Visibility.Visible;
            //mainGrid.ColumnDefinitions[1].MinWidth = 200;
            tabControl1.Visibility = Visibility.Visible;
        }

        private void deviceinStackButton_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            deviceTabItem.Visibility = Visibility.Visible;
            deviceinStackButton.Visibility = Visibility.Collapsed;
            tabControl1.SelectedIndex = 1;
            tabControl1.Width = Double.NaN;
            isFloawable = false;
            splitter1.Visibility = Visibility.Visible;
            // mainGrid.ColumnDefinitions[1].MinWidth = 200;
            tabControl1.Visibility = Visibility.Visible;
        }

        private void routeinStackButton_Click(object sender, RoutedEventArgs e)
        {
            if (isFloawable)
            {
                if (deviceTabItem.Visibility == Visibility.Collapsed)
                {
                    if (routTabItem.Visibility == Visibility.Visible)
                        routTabItem.Visibility = Visibility.Hidden;
                    else
                        mainGrid.Children.Add(splitter1);
                    routTabItem.Visibility = Visibility.Visible;
                    tabControl1.Visibility = Visibility.Visible;
                    tabControl1.Width = 200;
                    //   mainGrid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Auto);
                }
            }
        }

        private void tabControl1_MouseLeave(object sender, MouseEventArgs e)
        {
            if (isFloawable)
            {
                tabControl1.Visibility = Visibility.Collapsed;
                routTabItem.Visibility = Visibility.Collapsed;
                deviceTabItem.Visibility = Visibility.Collapsed;
                mainGrid.Children.Remove(splitter1);
                //  mainGrid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);
            }
        }

        private void deviceinStackButton_Click(object sender, RoutedEventArgs e)
        {
            if (isFloawable)
            {
                if (deviceTabItem.Visibility == Visibility.Collapsed)
                {
                    if (routTabItem.Visibility == Visibility.Visible)
                        routTabItem.Visibility = Visibility.Hidden;
                    else
                        mainGrid.Children.Add(splitter1);
                    deviceTabItem.Visibility = Visibility.Visible;
                    tabControl1.Visibility = Visibility.Visible;
                    tabControl1.Width = 200;
                    //  mainGrid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Auto);
                }
            }
        }
        #endregion
        #region Взаимодействие с канвой
        void canvas_SelectionChanged(object obj)
        {
            if (canvas.SelectedPoints.Count > 0)
            {
                if (canvas.SelectedPoints.Count == 1)
                {
                    PointControl p = canvas.SelectedPoints.First();
                    if (p.PreviousShape is Rectangle)
                        SetRectangleScrollViewerParameters(p);
                    else if (p.PreviousShape is Line)
                        SetlineScrollViewerParameters(ref p.Parameters);
                }
                else
                {
                    bool[] selectedHasFigures = new bool[2];
                    foreach (PointControl p in canvas.SelectedPoints)
                        if (p.PreviousShape is Line)
                            selectedHasFigures[0] = true;
                        else if (p.PreviousShape is Rectangle)
                            selectedHasFigures[1] = true;
                    if (selectedHasFigures[0] == false)
                        SetRectangleScrollViewerParameters();
                    else
                        SetlineScrollViewerParameters();
                }
            }
            else
            {
                commonPrtsExpander.Visibility = Visibility.Collapsed;
                synchronizationExpander.Visibility = Visibility.Collapsed;
                backlashExpander.Visibility = Visibility.Collapsed;
                okButton.Visibility = Visibility.Collapsed;
                rectangleExpander.Visibility = Visibility.Collapsed;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            canvas.PlaceableElement = SelectedElement.Line;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)//RECTANGLE
        {
            canvas.PlaceableElement = SelectedElement.RectangleArea;
        }
        private void gridItem_Click(object sender, RoutedEventArgs e)
        {
            GridSelectionWindow w = new GridSelectionWindow(this, canvas.GridStep);
            if (w.ShowDialog() == true)
            {
                canvas.GridStep = w.Value;
            }
        }

        private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            canvas.ZoomSLiderValue += (double)e.Delta / 100;
        }
        #endregion
        #region параметры линии
        private void lineTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                okButton_Click(null, null);
            }
        }
        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            if (rectangleExpander.IsVisible == false)
            {
                ApplyElementParameters();
                Trace.WriteLine("Параметры линии применены");
                SetlineScrollViewerParameters();
            }
            else
            {
                ApplyRectParameters();
                Trace.WriteLine("Параметры прямоугольника применены");
                SetRectangleScrollViewerParameters();
            }
        }
        //применяет параметры элемента к выбранным элементам
        private void ApplyElementParameters()
        {
            ApplyLineParams();
            lineScrollViewer.ScrollToTop();
        }

        private void ApplyLineParams()
        {
            double x = 0;
            double y = 0;
            Update update = null;
            byte divisor = 0;
            if (this.divisorComboBox.SelectedIndex != -1)
                divisor = (byte)Math.Pow(2, divisorComboBox.SelectedIndex);
            if (this.xTextBox.Text != "")
            {
                if (Double.TryParse(xTextBox.Text, out x))
                {
                    if (x % 1 != 0)
                    {
                        MessageBox.Show("Некорректный параметр X");
                        return;
                    }
                    foreach (PointControl p in canvas.SelectedPoints)
                    {
                        if (divisor != 0 && divisor != p.Parameters.StepDivisor && p.XSteps == x)
                            p.XSteps = (x * divisor) / p.Parameters.StepDivisor;
                        else
                            p.XSteps = x;
                        if (p.XSteps > canvas.MaxSteps * divisor)
                            p.XSteps = canvas.MaxSteps * divisor;
                        if (p.XSteps < 0)
                            p.XSteps = 0;
                    }
                    canvas.standardParameters.StepX = x;
                }
                else
                {
                    MessageBox.Show("Некорректный параметр X");
                    return;
                }
            }
            else
                if (divisor != 0)
                    foreach (PointControl p in canvas.SelectedPoints)
                        p.XSteps = p.XSteps * divisor / p.Parameters.StepDivisor;
            if (this.yTextBox.Text != "")
            {
                if (Double.TryParse(yTextBox.Text, out y))
                {
                    if (y % 1 != 0)
                    {
                        MessageBox.Show("Некорректный параметр Y");
                        return;
                    }
                    foreach (PointControl p in canvas.SelectedPoints)
                    {
                        if (divisor != 0 && divisor != p.Parameters.StepDivisor && p.YSteps == y)
                            p.YSteps = (y * divisor) / p.Parameters.StepDivisor;
                        else
                            p.YSteps = y;
                        if (p.YSteps > canvas.MaxSteps * divisor)
                            p.YSteps = canvas.MaxSteps * divisor;
                        if (p.YSteps < 0)
                            p.YSteps = 0;
                    }
                    canvas.standardParameters.StepY = y;
                }
                else
                {
                    MessageBox.Show("Некорректный параметр Y");
                    return;
                }
            }
            else
                if (divisor != 0)
                    foreach (PointControl p in canvas.SelectedPoints)
                        p.YSteps = p.YSteps * divisor / p.Parameters.StepDivisor;
            if (divisor != 0)
                foreach (PointControl p in canvas.SelectedPoints)
                    p.Parameters.StepDivisor = divisor;
            if (this.speedTextBox.Text != "")
            {
                float sped = 0;
                if (float.TryParse(speedTextBox.Text, out sped))
                {
                    foreach (PointControl p in canvas.SelectedPoints)
                        p.Parameters.Speed = sped;
                    canvas.standardParameters.Speed = sped;
                }
                else
                {
                    MessageBox.Show("Некорректный параметр скорость");
                    return;
                }
            }
            if (pauseTextBox.Text != "")
            {
                int t = 0;
                if (Int32.TryParse(pauseTextBox.Text, out t))
                {
                    //if (canvas.SelectedPoints.Count > 1)
                    //    if (MessageBox.Show("Вы точно хотите установить задержки для всех выбранных элементов?", "Внимание", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    //        return;
                    foreach (PointControl p in canvas.SelectedPoints)
                        p.Parameters.Pause = t;
                }
            }
            if (this.syncrInComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) =>
                {
                    p.WaitInputSync1 = (syncrInComboBox.SelectedIndex == 0);
                    p.WaitInputSync2 = p.WaitInputSync1;
                };
            if (this.syncrOutRComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) =>
                {
                    p.OutSyncCounterRes2 = (syncrOutRComboBox.SelectedIndex == 0);
                    p.OutSyncCounterRes1 = p.OutSyncCounterRes2;
                };
            if (slowStartComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) =>
                {
                    p.SlowStart1 = (slowStartComboBox.SelectedIndex == 0);
                    p.SlowStart2 = p.SlowStart1;
                };
            if (forceLoftComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) =>
                {
                    p.ForceLoft2 = (forceLoftComboBox.SelectedIndex != -1);
                    p.ForceLoft1 = p.ForceLoft2;
                };
            if (xBLDirComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) => { p.BacklashDirX = (xBLDirComboBox.SelectedIndex == 0); };
            if (yBLDirComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) => { p.BacklashDirY = (yBLDirComboBox.SelectedIndex == 0); };
            if (autoBackLashComboBox.SelectedIndex != -1)
                update += (ref PointParameters p) =>
                {
                    p.AutoBacklash2 = (autoBackLashComboBox.SelectedIndex == 0);
                    p.AutoBacklash1 = p.AutoBacklash2;
                };
            update(ref canvas.standardParameters);
            foreach (PointControl p in canvas.SelectedPoints)
            {
                update(ref p.Parameters);
                p.UpdateCoordinates();
            }
        }
        private void UnSetLineParameters()
        {
            this.xTextBox.Text = "";
            this.yTextBox.Text = "";
            this.syncrInComboBox.SelectedIndex = -1;
            this.speedTextBox.Text = "";
            this.pauseTextBox.Text = "";
            this.slowStartComboBox.SelectedIndex = -1;
            this.syncrOutRComboBox.SelectedIndex = -1;
            this.forceLoftComboBox.SelectedIndex = -1;
            this.xBLDirComboBox.SelectedIndex = -1;
            this.yBLDirComboBox.SelectedIndex = -1;
            this.autoBackLashComboBox.SelectedIndex = -1;
            this.divisorComboBox.SelectedIndex = -1;
        }

        private void SetlineScrollViewerParameters(ref PointParameters pointParameters)
        {
            this.xTextBox.Text = pointParameters.StepX.ToString();
            this.yTextBox.Text = pointParameters.StepY.ToString();
            if (pointParameters.WaitInputSync1)
                this.syncrInComboBox.SelectedIndex = 0;
            else
                this.syncrInComboBox.SelectedIndex = 1;
            this.speedTextBox.Text = pointParameters.Speed.ToString();
            this.pauseTextBox.Text = pointParameters.Pause.ToString();
            if (pointParameters.SlowStart1)
                this.slowStartComboBox.SelectedIndex = 0;
            else
                slowStartComboBox.SelectedIndex = 1;
            if (pointParameters.OutSyncCounterRes1)
                syncrOutRComboBox.SelectedIndex = 0;
            else
                syncrOutRComboBox.SelectedIndex = 1;
            if (pointParameters.ForceLoft1)
                forceLoftComboBox.SelectedIndex = 0;
            else
                forceLoftComboBox.SelectedIndex = 1;
            if (pointParameters.BacklashDirX)
                xBLDirComboBox.SelectedIndex = 0;
            else
                xBLDirComboBox.SelectedIndex = 1;
            if (pointParameters.BacklashDirY)
                yBLDirComboBox.SelectedIndex = 0;
            else
                yBLDirComboBox.SelectedIndex = 1;
            if (pointParameters.AutoBacklash1)
                autoBackLashComboBox.SelectedIndex = 0;
            else
                autoBackLashComboBox.SelectedIndex = 1;
            switch (pointParameters.StepDivisor)
            {
                case 1:
                    this.divisorComboBox.SelectedIndex = 0;
                    break;
                case 2:
                    this.divisorComboBox.SelectedIndex = 1;
                    break;
                case 4:
                    this.divisorComboBox.SelectedIndex = 2;
                    break;
                case 8:
                    this.divisorComboBox.SelectedIndex = 3;
                    break;
            }
            commonPrtsExpander.Visibility = Visibility.Visible;
            synchronizationExpander.Visibility = Visibility.Visible;
            backlashExpander.Visibility = Visibility.Visible;
            rectangleExpander.Visibility = Visibility.Collapsed;
            okButton.Visibility = Visibility.Visible;
        }
        //устанавливает значения базовых текстбоксов исходя из параметров всех выбранных точек
        private void SetlineScrollViewerParameters()
        {
            double t = canvas.SelectedPoints[0].XSteps;
            int i = 1;
            int max = canvas.SelectedPoints.Count;
            bool isOne = true;
            while (i < max && isOne)
                isOne = (t == canvas.SelectedPoints[i++].XSteps);
            if (isOne)
                this.xTextBox.Text = t.ToString();
            else
                this.xTextBox.Text = "";

            t = canvas.SelectedPoints[0].Parameters.Pause;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (t == canvas.SelectedPoints[i++].Parameters.Pause);
            if (isOne)
                this.pauseTextBox.Text = t.ToString();
            else
                this.pauseTextBox.Text = "";

            t = canvas.SelectedPoints[0].YSteps;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (t == canvas.SelectedPoints[i++].YSteps);
            if (isOne)
                this.yTextBox.Text = t.ToString();
            else
                this.yTextBox.Text = "";

            bool b = canvas.SelectedPoints[0].Parameters.WaitInputSync1;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.WaitInputSync1);
            if (isOne)
            {
                if (b)
                    this.syncrInComboBox.SelectedIndex = 0;
                else
                    this.syncrInComboBox.SelectedIndex = 1;
            }
            else
                syncrInComboBox.SelectedIndex = -1;

            t = canvas.SelectedPoints[0].Parameters.Speed;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (t == canvas.SelectedPoints[i++].Parameters.Speed);
            if (isOne)
                this.speedTextBox.Text = t.ToString();
            else
                speedTextBox.Text = "";

            b = canvas.SelectedPoints[0].Parameters.SlowStart1;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.SlowStart1);
            if (isOne)
            {
                if (b)
                    this.slowStartComboBox.SelectedIndex = 0;
                else
                    this.slowStartComboBox.SelectedIndex = 1;
            }
            else
                slowStartComboBox.SelectedIndex = -1;

            b = canvas.SelectedPoints[0].Parameters.OutSyncCounterRes1;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.OutSyncCounterRes1);
            if (isOne)
            {
                if (b)
                    this.syncrOutRComboBox.SelectedIndex = 0;
                else
                    this.syncrOutRComboBox.SelectedIndex = 1;
            }
            else
                syncrOutRComboBox.SelectedIndex = -1;

            b = canvas.SelectedPoints[0].Parameters.ForceLoft1;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.ForceLoft1);
            if (isOne)
            {
                if (b)
                    this.forceLoftComboBox.SelectedIndex = 0;
                else
                    this.forceLoftComboBox.SelectedIndex = 1;
            }
            else
                forceLoftComboBox.SelectedIndex = -1;

            b = canvas.SelectedPoints[0].Parameters.BacklashDirX;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.BacklashDirX);
            if (isOne)
            {
                if (b)
                    this.xBLDirComboBox.SelectedIndex = 0;
                else
                    this.xBLDirComboBox.SelectedIndex = 1;
            }
            else
                xBLDirComboBox.SelectedIndex = -1;

            b = canvas.SelectedPoints[0].Parameters.BacklashDirY;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.BacklashDirY);
            if (isOne)
            {
                if (b)
                    this.yBLDirComboBox.SelectedIndex = 0;
                else
                    this.yBLDirComboBox.SelectedIndex = 1;
            }
            else
                yBLDirComboBox.SelectedIndex = -1;

            b = canvas.SelectedPoints[0].Parameters.AutoBacklash1;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (b == canvas.SelectedPoints[i++].Parameters.AutoBacklash1);
            if (isOne)
            {
                if (b)
                    this.autoBackLashComboBox.SelectedIndex = 0;
                else
                    this.autoBackLashComboBox.SelectedIndex = 1;
            }
            else
                autoBackLashComboBox.SelectedIndex = -1;

            byte divisor = canvas.SelectedPoints[0].Parameters.StepDivisor;
            i = 1;
            isOne = true;
            while (i < max && isOne)
                isOne = (divisor == canvas.SelectedPoints[i++].Parameters.StepDivisor);
            if (isOne)
            {
                switch (divisor)
                {
                    case 1:
                        this.divisorComboBox.SelectedIndex = 0;
                        break;
                    case 2:
                        this.divisorComboBox.SelectedIndex = 1;
                        break;
                    case 4:
                        this.divisorComboBox.SelectedIndex = 2;
                        break;
                    case 8:
                        this.divisorComboBox.SelectedIndex = 3;
                        break;
                }
            }
            else
                divisorComboBox.SelectedIndex = -1;
            commonPrtsExpander.Visibility = Visibility.Visible;
            synchronizationExpander.Visibility = Visibility.Visible;
            backlashExpander.Visibility = Visibility.Visible;
            rectangleExpander.Visibility = Visibility.Collapsed;
            okButton.Visibility = Visibility.Visible;
        }

        private void autoBackLashComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (autoBackLashComboBox.SelectedIndex == 0 && slowStartComboBox.SelectedIndex == 0)
            {
                slowStartComboBox.SelectedIndex = 1;
            }
        }

        private void slowStartComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (autoBackLashComboBox.SelectedIndex == 0 && slowStartComboBox.SelectedIndex == 0)
            {
                autoBackLashComboBox.SelectedIndex = 1;
            }
        }
        #endregion
        #region параметры прямоугольника
        //установка значений прямоугольника
        private void SetRectangleScrollViewerParameters(PointControl p)
        {
            SetlineScrollViewerParameters(ref p.Parameters);
            rectangleExpander.Visibility = Visibility.Visible;
            double x = p.XSteps - p.PrevPoint.XSteps;
            if (x >= 0)
                x++;
            else
                x--;
            rectangleWidthTextBox.Text = x.ToString();
            double y=p.YSteps - p.PrevPoint.YSteps;
            if(y>=0)
                y++;
            else
                y--;
            rectangleHeightTextBox.Text = y.ToString();
            RectangleParameters rePar = (RectangleParameters)p.ShapeParameters;
            rectDirectionComboBox.SelectedIndex = rePar.Dir?1:0;
            rectIntTextBox.Text = rePar.Shift.ToString();
        }
        private void SetRectangleScrollViewerParameters()
        {
            SetlineScrollViewerParameters();
            rectangleExpander.Visibility = Visibility.Visible;
            bool identical = true;
            int index=1;
            double x = canvas.SelectedPoints.First().XSteps - canvas.SelectedPoints.First().PrevPoint.XSteps;
            while (identical && index < canvas.SelectedPoints.Count)
            {
                double k = canvas.SelectedPoints[index].XSteps - canvas.SelectedPoints[index].PrevPoint.XSteps;
                if (k != x)
                    identical = false;
                index++;
            }
            if (identical)
            {
                if (x >= 0)
                    x++;
                else
                    x--;
                rectangleWidthTextBox.Text = x.ToString();
            }
            else
                rectangleWidthTextBox.Text = "";
            identical = true;
            index = 1;
            double y = canvas.SelectedPoints.First().YSteps - canvas.SelectedPoints.First().PrevPoint.YSteps;
            while (identical && index < canvas.SelectedPoints.Count)
            {
                double k = canvas.SelectedPoints[index].YSteps - canvas.SelectedPoints[index].PrevPoint.YSteps;
                if (k != x)
                    identical = false;
                index++;
            }
            if (identical)
            {
                if (y >= 0)
                    y++;
                else
                    y--;
                rectangleHeightTextBox.Text = x.ToString();
            }
            else
                rectangleHeightTextBox.Text = "";
            RectangleParameters rePar = (RectangleParameters)canvas.SelectedPoints[0].ShapeParameters;
            index = 1;
            identical = true;
            bool identical2=true;
            RectangleParameters r;
            while ((identical||identical2) && index < canvas.SelectedPoints.Count)
            {
                r = (RectangleParameters)canvas.SelectedPoints[index].ShapeParameters;
                if (r.Dir != rePar.Dir)
                    identical = false;
                if (r.Shift != rePar.Shift)
                    identical2 = false;
                index++;
            }
            if (identical)
                rectDirectionComboBox.SelectedIndex = rePar.Dir ? 1 : 0;
            else
                rectDirectionComboBox.SelectedIndex = -1;
            if (identical2)
                rectIntTextBox.Text = rePar.Shift.ToString();
            else
                rectIntTextBox.Text = "";
        }
        private void ApplyRectParameters()
        {
            try
            {
                ApplyElementParameters();
                int shift = Int32.Parse(rectIntTextBox.Text);
                bool dir;
                if (rectDirectionComboBox.SelectedIndex == -1)
                    throw new Exception();
                else
                    dir = (rectDirectionComboBox.SelectedIndex == 1);
                RectangleParameters par = new RectangleParameters { Dir = dir, Shift = shift };
                foreach (PointControl p in canvas.SelectedPoints)
                {
                    p.AssignShapeParameters(par);
                }
            }
            catch
            {
                MessageBox.Show("Неверные параметры!", "Ошибка");
                Trace.WriteLine("Ошибка в параметрах");
            }
        }
        #endregion
        #region Движение
        private void startItem_Click(object sender, RoutedEventArgs e)
        {
            Action action = () =>
                {
                    checker = new Checker();
                    checker.IsCancelled = false;
                    PointControl point = canvas.StartPoint;
                    IPathElement pathElement = null;
                    while (point != null)
                    {
                        if (canvas.dev.SyncCountReset1 || canvas.dev.SyncCountReset2)
                        {
                            canvas.dev.GetMODE();
                            if (canvas.dev.SyncCountReset1)
                                canvas.dev.MODE[0].SyncOUTR = true;
                            if (canvas.dev.SyncCountReset2)
                                canvas.dev.MODE[1].SyncOUTR = true;
                            canvas.dev.SetMODE();
                        }
                        if (point.PreviousShape is Line)
                        {
                            pathElement = new BaseLine((int)point.XSteps, (int)point.YSteps, point.Parameters.Speed, new StartPRMSLine[] { point.Parameters.st1, point.Parameters.st2 }, canvas.dev);
                            Trace.WriteLine("Движение по линии " + ((int)point.XSteps).ToString() + " " + ((int)point.YSteps).ToString() + " началось");
                        }
                        else if (point.PreviousShape is Rectangle)
                        {
                            RectangleParameters rp = (RectangleParameters)point.ShapeParameters;
                            pathElement = new BaseRectangle((int)point.XSteps, (int)point.YSteps, rp.Shift, point.Parameters.Speed, new StartPRMSLine[] { point.Parameters.st1, point.Parameters.st2 }, canvas.dev, rp.Dir,checker);
                            Trace.WriteLine("Движение по прямоугольнику " + ((int)point.XSteps).ToString() + " " + ((int)point.YSteps).ToString() + " началось");
                        }
                        pathElement.Move();
                        Trace.WriteLine("Пауза " + point.Parameters.Pause.ToString() + " млс.");
                        System.Threading.Thread.Sleep(point.Parameters.Pause);
                        point = point.NextPoint;
                    }
                    if (canvas.dev.ShutDownWhenFinished)
                    {
                        //TODO:проверить таймер
                        EventHandler handler = (object s, EventArgs ev) =>
                            {
                                this.Close();
                            };
                        shutDownTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, (int)canvas.dev.ShutDownTime), DispatcherPriority.ApplicationIdle, handler, Dispatcher);
                        shutDownTimer.Start();
                        MouseEventHandler h1 = null;
                        MouseButtonEventHandler h2 = null;
                        KeyEventHandler h3 = null;
                        h1 = (object s, MouseEventArgs args) =>
                            {
                                shutDownTimer.Stop();
                                this.MouseMove -= h1;
                                this.MouseDown -= h2;
                                this.KeyDown -= h3;
                            };
                        h2 = (object s, MouseButtonEventArgs args) =>
                            {
                                shutDownTimer.Stop();
                                this.MouseMove -= h1;
                                this.MouseDown -= h2;
                                this.KeyDown -= h3;
                            };
                        h3 = (object s, KeyEventArgs args) =>
                            {
                                shutDownTimer.Stop();
                                this.MouseMove -= h1;
                                this.MouseDown -= h2;
                                this.KeyDown -= h3;
                            };
                        this.MouseMove += h1;
                        this.MouseDown += h2;
                        this.KeyDown += h3;
                    }
                };
            movementCancel = new System.Threading.CancellationTokenSource();
            var task = Task.Factory.StartNew(action, movementCancel.Token);
            
        }

        private void stopMenuItem_Click(object sender, RoutedEventArgs e) //вроде ок
        {
            if (movementCancel != null)
            {
                movementCancel.Cancel();
                checker.IsCancelled = true;
            }
            

            canvas.dev.Stop();
        }
        #endregion
        #region Меню
        private void showCurrentItem_Click(object sender, RoutedEventArgs e)
        {
            if (showCurrentItem.IsChecked == false)
                canvas.mainCanvas.Children.Remove(canvas.currentPosImage);
            else
                canvas.mainCanvas.Children.Add(canvas.currentPosImage);
        }
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
                   // canvas.dev.Calibrate();
            Trace.WriteLine("Калибровка...");
            BaseLine bl = new BaseLine(500000, 500000, 2000, new StartPRMSLine[] { canvas.standardParameters.st1, canvas.standardParameters.st2 }, canvas.dev);
                    bl.StPrms[0].Step = 1;
                    bl.StPrms[1].Step = 1;
                    bl.Move();
                    canvas.dev.GetSTATE();
                    canvas.MaxSteps=canvas.dev.STATE[0].CurPos > canvas.dev.STATE[1].CurPos ? canvas.dev.STATE[1].CurPos : canvas.dev.STATE[0].CurPos;
                    Trace.WriteLine("Калибровка завершена");
        }
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            ParametersWindow pw = new ParametersWindow(canvas.dev);
            pw.ShowDialog();
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                if (e.Key == Key.F)
                {
                    fileItem.IsSubmenuOpen = true;
                    fileItem.Focus();
                }
            }
            if (e.Key == Key.Delete)
            {
                canvas.RemoveSelected();
            }
        }


        private void Window_Closed(object sender, EventArgs e) //косячит у концевиков
        {
            canvas.dev.Stop();
            canvas.dev.GetMODE();
            canvas.dev.MODE[0].Power = false;
            canvas.dev.MODE[1].Power = false;
            canvas.dev.SetMODE();
        }

        private void toStartMenuItem_Click(object sender, RoutedEventArgs e) //WTF??
        {
            Trace.WriteLine("Движение в начало координат...");
            IPathElement line = new BaseLine((int)(canvas.StartPoint.XSteps), (int)(canvas.StartPoint.YSteps), canvas.standardParameters.Speed, new StartPRMSLine[] { canvas.StartPoint.Parameters.st1, canvas.StartPoint.Parameters.st2 }, canvas.dev);
            var task = Task.Factory.StartNew(line.Move);           
        }

        private void restartMicroSMC_Click(object sender, RoutedEventArgs e)//крешится из-за таймера
        {
            timer.Stop();
            canvas.dev.CloseMicroSMCexe();
            Process p = new Process();
            p.StartInfo.FileName = ("C:\\Program Files\\MicroSMC\\Restart MicroSMC.lnk");
            p.Start();
            canvas.dev = new Devices();
            canvas.dev.GetMODE();
            canvas.dev.MODE[0].Power = true;
            canvas.dev.MODE[1].Power = true;
            canvas.dev.SetMODE();
            timer.Start();
        }
        #endregion
        #region Обновление данных об устройстве
        TextBlock[] stateDefTextBoxes = new TextBlock[33];
        TextBlock[] stateParTextBoxes = new TextBlock[33];
        TextBlock[] modeDefTextBoxes;
        ComboBox[] modeParComboBoxes;
        TextBox stepsForImpulse1;
        TextBox stepsForImpulse2;
        CheckBox[] modeParCheckBoxes;
        TextBlock[] parametersDefs;
        TextBox[] parametersVals;
        private void timerTick(object sender, EventArgs e)
        {
            canvas.dev.GetSTATE();
            string temp = " ";
            if (canvas.dev.STATE[0].Power) temp += "On";
            else temp += "Off";
            if (canvas.dev.STATE[1].Power) temp += " On";
            else temp += " Off";
            deviceStateBarItem.Content = (temp);
            temp = canvas.dev.STATE[0].Temp.ToString();
            temp += (" " + canvas.dev.STATE[1].Temp.ToString());
            temperatureBarItem.Content = (object)(temp);
            temp = canvas.dev.STATE[0].CurPos.ToString();
            temp += (" " + canvas.dev.STATE[1].CurPos.ToString());
            if (canvas.dev.STATE[0].Temp > 100 || canvas.dev.STATE[0].Temp < -50 || canvas.dev.STATE[1].Temp > 100 || canvas.dev.STATE[1].Temp < -50) currentPositionBarItem.Content = (object)("Устройство не подключено");
            else currentPositionBarItem.Content = (object)(temp);
            if (tabControl1.SelectedIndex == 1)
            {
                if (stateExpander.IsExpanded)
                    FillStateTextBoxes();
                if (encoderExpander.IsExpanded)
                {
                    if (canvas.dev.MODE[0].EncoderEn && canvas.dev.MODE[1].EncoderEn)
                    {
                        EncoderPosTextBox.Text = canvas.dev.ENCODER[0].EncoderPos.ToString() + " " + canvas.dev.ENCODER[1].EncoderPos.ToString();
                        ECurPosTextBox.Text = canvas.dev.ENCODER[0].ECurPos.ToString() + " " + canvas.dev.ENCODER[1].ECurPos.ToString();
                    }
                    else
                    {
                        EncoderPosTextBox.Text = "энкодер не активирован";
                        ECurPosTextBox.Text = "энкодер не активирован";
                    }
                }
            }
            Canvas.SetLeft(canvas.currentPosImage, canvas.stepsXToPos(canvas.dev.STATE[0].CurPos / 8) - canvas.currentPosImage.Width / (2*canvas.Zoom));
            Canvas.SetTop(canvas.currentPosImage, canvas.stepsYToPos(canvas.dev.STATE[1].CurPos / 8) - canvas.currentPosImage.Height / (2*canvas.Zoom));
        }
        private void InitializeParametersBoxes()
        {
            parametersDefs = new TextBlock[ParametersNames.ParametersDefs.Length];
            parametersVals = new TextBox[parametersDefs.Length];
            Grid.SetRowSpan(paramGridSplitter, parametersDefs.Length);
            for (int i = 0; i < ParametersNames.ParametersDefs.Length; i++)
            {
                parametersDefs[i] = new TextBlock();
                parametersDefs[i].TextWrapping = TextWrapping.Wrap;
                parametersDefs[i].Text = ParametersNames.ParametersDefs[i];
                parametersDefs[i].AllowDrop = false;
                parametersDefs[i].Focusable = false;
                parametersDefs[i].Margin = new Thickness(1);
                parametersDefs[i].Background = Brushes.White;
                Grid.SetColumn(parametersDefs[i], 0);
                Grid.SetRow(parametersDefs[i], i + 1);
                parametersGrid.RowDefinitions.Add(new RowDefinition());
                parametersGrid.Children.Add(parametersDefs[i]);

                parametersVals[i] = new TextBox();
                parametersVals[i].TextWrapping = TextWrapping.Wrap;
                if (i % 2 == 1)
                {
                    parametersDefs[i].Background = tabControl1.Background;
                    parametersVals[i].Background = tabControl1.Background;
                }
                Grid.SetColumn(parametersVals[i], 1);
                Grid.SetRow(parametersVals[i], i + 1);
                parametersGrid.Children.Add(parametersVals[i]);
            }
            Grid.SetZIndex(paramGridSplitter, 100);
        }
        private void parametersExpande_Expanded(object sender, RoutedEventArgs e)
        {
            UpdateParametersTextBox();
        }

        private void refreshParamButton_Click(object sender, RoutedEventArgs e)
        {
            UpdateParametersTextBox();
        }

        private void UpdateParametersTextBox()
        {
            canvas.dev.GetPRMS();
            parameters[] p = canvas.dev.PRMS;
            float[] array = new float[parametersDefs.Length];
            //array[0] = p[0].MinP;
            //array[1] = p[1].MinP;
            array[2] = p[0].MaxLoft;
            array[3] = p[1].MaxLoft;
            array[4] = p[0].RTDelta;
            array[5] = p[1].RTDelta;
            array[6] = p[0].RTMinError;
            array[7] = p[1].RTMinError;
            array[8] = p[1].MaxTemp > p[0].MaxTemp ? p[0].MaxTemp : p[1].MaxTemp;
            /*    array[9] = p[0].SyncOUTP;
                   array[10] = p[1].SyncOUTP;
                   array[11] = p[0].LoftPeriod;
                   array[12] = p[1].LoftPeriod;
                   array[13] = p[0].EncMult;
                   array[14] = p[1].EncMult;*/
            for (int i = 0; i < array.Length; i++)
            {
                parametersVals[i].Text = array[i].ToString();
            }
        }
        private void InitializeStateTextBoxes()
        {
            for (int i = 0; i < ParametersNames.StateDefs.Length; i++)
            {
                stateDefTextBoxes[i] = new TextBlock();
                stateDefTextBoxes[i].TextWrapping = TextWrapping.Wrap;
                stateDefTextBoxes[i].Text = ParametersNames.StateDefs[i];
                stateGrid.RowDefinitions.Add(new RowDefinition());
                Grid.SetColumn(stateDefTextBoxes[i], 0);
                Grid.SetRow(stateDefTextBoxes[i], i);
                stateGrid.Children.Add(stateDefTextBoxes[i]);
                stateParTextBoxes[i] = new TextBlock();
                stateParTextBoxes[i].TextWrapping = TextWrapping.Wrap;
                Grid.SetRow(stateParTextBoxes[i], i);
                Grid.SetColumn(stateParTextBoxes[i], 1);
                stateGrid.Children.Add(stateParTextBoxes[i]);
                if (i % 2 == 0)
                {
                    stateDefTextBoxes[i].Background = Brushes.White;
                    stateParTextBoxes[i].Background = Brushes.White;
                }
                stateDefTextBoxes[i].Focusable = false;
                stateDefTextBoxes[i].AllowDrop = false;
                stateParTextBoxes[i].Focusable = false;
                stateParTextBoxes[i].AllowDrop = false;
            }
            Grid.SetRow(stateGridSplitter, 0);
            Grid.SetZIndex(stateGridSplitter, 100);
            Grid.SetRowSpan(stateGridSplitter, stateGrid.RowDefinitions.Count);
        }
        private void FillStateTextBoxes()
        {
            stateParTextBoxes[0].Text = "(" + canvas.dev.STATE[0].CurPos + ", " + canvas.dev.STATE[1].CurPos + ")";
            stateParTextBoxes[1].Text = canvas.dev.STATE[0].Temp + ", " + canvas.dev.STATE[1].Temp;
            stateParTextBoxes[2].Text = canvas.dev.STATE[0].SDivisor + ", " + canvas.dev.STATE[1].SDivisor;
            stateParTextBoxes[3].Text = canvas.dev.STATE[0].Voltage.ToString();
            stateParTextBoxes[4].Text = canvas.dev.STATE[1].Voltage.ToString();
            bool[] array = new bool[stateParTextBoxes.Length - 5];
            array[0] = canvas.dev.STATE[0].Power;
            array[1] = canvas.dev.STATE[1].Power;
            array[2] = canvas.dev.STATE[0].FullPower;
            array[3] = canvas.dev.STATE[1].FullPower;
            array[4] = canvas.dev.STATE[0].FullSpeed;
            array[5] = canvas.dev.STATE[1].FullSpeed;
            array[6] = canvas.dev.STATE[0].Loft;
            array[7] = canvas.dev.STATE[1].Loft;
            array[8] = canvas.dev.STATE[0].CW_CCW;
            array[9] = canvas.dev.STATE[1].CW_CCW;
            array[10] = canvas.dev.STATE[0].AReset;
            array[11] = canvas.dev.STATE[1].AReset;
            array[12] = canvas.dev.STATE[0].RUN;
            array[13] = canvas.dev.STATE[1].RUN;
            array[14] = canvas.dev.STATE[0].SyncIN;
            array[15] = canvas.dev.STATE[1].SyncIN;
            array[16] = canvas.dev.STATE[0].SyncOUT;
            array[17] = canvas.dev.STATE[1].SyncOUT;
            array[18] = canvas.dev.STATE[0].RotTr;
            array[19] = canvas.dev.STATE[1].RotTr;
            array[20] = canvas.dev.STATE[0].RotTrErr;
            array[21] = canvas.dev.STATE[1].RotTrErr;
            array[22] = canvas.dev.STATE[0].EmReset;
            array[23] = canvas.dev.STATE[1].EmReset;
            array[24] = canvas.dev.STATE[0].Trailer1;
            array[25] = canvas.dev.STATE[0].Trailer2;
            array[26] = canvas.dev.STATE[1].Trailer1;
            array[27] = canvas.dev.STATE[1].Trailer2;
            for (int i = 5; i < stateParTextBoxes.Length; i++)
            {
                if (array[i - 5])
                    stateParTextBoxes[i].Text = ParametersNames.StateTrueVals[i - 5];
                else
                    stateParTextBoxes[i].Text = ParametersNames.StateFalseVals[i - 5];
            }
        }
        private void InitializeModeTextBoxes()
        {
            modeDefTextBoxes = new TextBlock[ParametersNames.ModeDefs.Length - 9];
            modeParCheckBoxes = new CheckBox[9];
            modeParComboBoxes = new ComboBox[ParametersNames.ModeYesVals.Length];
            for (int i = modeDefTextBoxes.Length; --i >= 0; )
            {
                modeDefTextBoxes[i] = new TextBlock();
                modeDefTextBoxes[i].TextWrapping = TextWrapping.Wrap;
                modeDefTextBoxes[i].Text = ParametersNames.ModeDefs[i];
                if (i % 2 == 0)
                    modeDefTextBoxes[i].Background = Brushes.White;
                modeDefTextBoxes[i].Focusable = false;
                modeDefTextBoxes[i].AllowDrop = false;
                Grid.SetColumn(modeDefTextBoxes[i], 0);
                Grid.SetRow(modeDefTextBoxes[i], i + 1);
                modeGrid.Children.Add(modeDefTextBoxes[i]);
                modeGrid.RowDefinitions.Add(new RowDefinition());
            }
            for (int i = 0; i < modeParCheckBoxes.Length; i++)
            {
                modeParCheckBoxes[i] = new CheckBox();
                TextBlock tb = new TextBlock();
                tb.TextWrapping = TextWrapping.Wrap;
                tb.AllowDrop = false;
                tb.Text = ParametersNames.ModeDefs[i + modeDefTextBoxes.Length];
                modeParCheckBoxes[i].Content = tb;
                Grid.SetColumnSpan(modeParCheckBoxes[i], 2);
                Grid.SetRow(modeParCheckBoxes[i], i + 1 + modeDefTextBoxes.Length);
                modeGrid.Children.Add(modeParCheckBoxes[i]);
                modeGrid.RowDefinitions.Add(new RowDefinition());
            }
            Grid.SetZIndex(modeGridSplitter, 200);
            Grid.SetRowSpan(modeGridSplitter, modeDefTextBoxes.Length);
            modeParComboBoxes = new ComboBox[31];
            for (int j = 0; j < 25; j++)
            {
                modeParComboBoxes[j] = new ComboBox();
                modeParComboBoxes[j].Background = modeDefTextBoxes[j].Background;
                modeParComboBoxes[j].Items.Add(ParametersNames.ModeYesVals[j]);
                modeParComboBoxes[j].Items.Add(ParametersNames.ModeNoVals[j]);
                Grid.SetColumn(modeParComboBoxes[j], 1);
                Grid.SetRow(modeParComboBoxes[j], j + 1);
                modeGrid.Children.Add(modeParComboBoxes[j]);
            }
            stepsForImpulse1 = new TextBox();
            stepsForImpulse1.Background = modeDefTextBoxes[26].Background;
            stepsForImpulse2 = new TextBox();
            stepsForImpulse2.Background = modeDefTextBoxes[27].Background;
            Grid.SetColumn(stepsForImpulse1, 1);
            Grid.SetRow(stepsForImpulse1, 26);
            modeGrid.Children.Add(stepsForImpulse1);
            Grid.SetColumn(stepsForImpulse2, 1);
            Grid.SetRow(stepsForImpulse2, 27);
            modeGrid.Children.Add(stepsForImpulse2);
            for (int j = 25; j < 31; j++)
            {
                modeParComboBoxes[j] = new ComboBox();
                modeParComboBoxes[j].Background = modeDefTextBoxes[j].Background;
                modeParComboBoxes[j].Items.Add(ParametersNames.ModeYesVals[j]);
                modeParComboBoxes[j].Items.Add(ParametersNames.ModeNoVals[j]);
                Grid.SetColumn(modeParComboBoxes[j], 1);
                Grid.SetRow(modeParComboBoxes[j], j + 3);
                modeGrid.Children.Add(modeParComboBoxes[j]);
            }
        }
        private void UpdateModeParams()
        {
            int[] array = new int[modeParComboBoxes.Length];
            canvas.dev.GetMODE();
            mode[] m = canvas.dev.MODE;
        }
        private void refreshModeButton_Click(object sender, RoutedEventArgs e)
        {
            UpdateModeParams();
        }
        private void modeExpander_Expanded(object sender, RoutedEventArgs e)
        {
            UpdateModeParams();
        }
        private void ApplyModeParams()
        {
            //TODO: доделать
        }
        #endregion

        private void applyModeButton_Click(object sender, RoutedEventArgs e)
        {
            ApplyModeParams();
        }

        private void logItem_Click(object sender, RoutedEventArgs e)
        {
            if (logItem.IsChecked)
            {
                logTextBox.Visibility = Visibility.Visible;
                logGridSplitter.Visibility = Visibility.Visible;
            }
            else
            {
                logGridSplitter.Visibility = Visibility.Collapsed;
                logTextBox.Visibility = Visibility.Collapsed;
                mainGrid.RowDefinitions[2].Height = new GridLength(1, GridUnitType.Auto);
            }
        }

        private void applyParamButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void canvas_LostFocus(object sender, RoutedEventArgs e)
        {
            if (canvas.SelectedPoints.Count > 0)
            {
                foreach (PointControl p in canvas.SelectedPoints)
                    p.ReleaseMouseCapture();
            }
            canvas.RemoveBufElement();
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            canvas.RemoveBufElement();
        }

        void point_KeyDown(object sender, KeyEventArgs e)
        {
            if (canvas.SelectedPoints.Count!=0)
            {
                PointControl p = canvas.SelectedPoints.Last<PointControl>();
                if (e.Key == Key.PageUp)
                {
                    if (Keyboard.Modifiers != ModifierKeys.Shift)
                        canvas.DeselectAll();
                    else
                    {
                        p.IsSelected = false;
                        canvas.SelectedPoints.Remove(p);
                    }
                    Canvas.SetZIndex(p, 0);
                    Canvas.SetZIndex(p.PreviousShape, 0);
                    Canvas.SetZIndex(p.NextInStack, 5);
                    Canvas.SetZIndex(p.NextInStack.PreviousShape, 5);
                    if (!p.NextInStack.IsSelected)
                    {
                        canvas.SelectedPoints.Add(p.NextInStack);
                        p.NextInStack.IsSelected = true;
                    }
                    canvas.pointsCanvas.UpdateLayout();
                    canvas.mainCanvas.UpdateLayout();
                }
                else if (e.Key == Key.PageDown)
                {
                    if (Keyboard.Modifiers != ModifierKeys.Shift)
                        canvas.DeselectAll();
                    else
                    {
                        p.IsSelected = false;
                        canvas.SelectedPoints.Remove(p);
                    }
                    PointControl c = p;
                    while (c.NextInStack != p)
                        c = c.NextInStack;
                    Canvas.SetZIndex(p, 0);
                    Canvas.SetZIndex(c, 5);
                    if (!c.IsSelected)
                    {
                        canvas.SelectedPoints.Add(c);
                        c.IsSelected = true;
                    }
                    canvas.pointsCanvas.UpdateLayout();
                    canvas.mainCanvas.UpdateLayout();
                }
                else
                    return;
                canvas_SelectionChanged(null);
                //e.Handled = true;
            }
        }

        private void cyclesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cyclesList.SelectedPoints.Count() > 0)
            {
                canvas.DeselectAll();
                foreach (PointControl pc in cyclesList.SelectedPoints)
                {
                    canvas.SelectedPoints.Add(pc);
                    pc.IsSelected = true;
                }
            }
        }

        private void gridRectButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (PointControl pc in canvas.SelectedPoints)
            {
                canvas.MakeRectangleGrid(pc);
            }
        }
    }
}
